import systemUserService, {
	type SystemUserItem,
} from "@/api/services/systemUserService";
import { PlusOutlined } from "@ant-design/icons";
import {
	Button,
	Card,
	Form,
	Input,
	Select,
	Space,
	Table,
	Tag,
	message,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import { useCallback, useEffect, useState } from "react";
import UserModal from "./user-modal";

const UserList = () => {
	const [form] = Form.useForm();
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState<SystemUserItem[]>([]);
	const [total, setTotal] = useState(0);
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(10);
	const [modalVisible, setModalVisible] = useState(false);
	const [currentUser, setCurrentUser] = useState<SystemUserItem | null>(null);

	const fetchUsers = useCallback(
		async (page = currentPage, limit = pageSize) => {
			try {
				setLoading(true);
				const values = await form.validateFields();
				const {
					data: { total, items },
				} = await systemUserService.userList({
					page,
					limit,
					...values,
				});
				setData(items);
				setTotal(total);
			} catch (error) {
				message.error("获取用户列表失败");
			} finally {
				setLoading(false);
			}
		},
		[currentPage, pageSize, form],
	);

	useEffect(() => {
		fetchUsers();
	}, [fetchUsers]);

	const handleDelete = async (id: number) => {
		try {
			await systemUserService.userDelete(id);
			message.success("删除成功");
			fetchUsers();
		} catch (error) {
			message.error("删除失败");
		}
	};

	const columns: ColumnsType<SystemUserItem> = [
		{
			title: "用户名",
			dataIndex: "username",
		},
		{
			title: "昵称",
			dataIndex: "nickname",
		},
		{
			title: "邮箱",
			dataIndex: "email",
		},
		{
			title: "手机号",
			dataIndex: "mobile",
		},
		{
			title: "角色",
			dataIndex: ["role", "name"],
		},
		{
			title: "状态",
			dataIndex: "status",
			render: (status: number) => (
				<Tag color={status === 1 ? "success" : "error"}>
					{status === 1 ? "启用" : "禁用"}
				</Tag>
			),
		},
		{
			title: "创建时间",
			dataIndex: "createtime",
			render: (time: number) =>
				dayjs(time * 1000).format("YYYY-MM-DD HH:mm:ss"),
		},
		{
			title: "操作",
			key: "action",
			render: (_, record) => (
				<Space size="middle">
					<Button
						type="link"
						onClick={() => {
							setCurrentUser(record);
							setModalVisible(true);
						}}
					>
						编辑
					</Button>
					<Button type="link" danger onClick={() => handleDelete(record.id)}>
						删除
					</Button>
				</Space>
			),
		},
	];

	return (
		<Card>
			<Form
				form={form}
				layout="inline"
				style={{ marginBottom: 16 }}
				onFinish={() => fetchUsers(1)}
			>
				<Form.Item name="username">
					<Input placeholder="用户名" allowClear />
				</Form.Item>
				<Form.Item name="status">
					<Select
						placeholder="状态"
						allowClear
						style={{ width: 120 }}
						options={[
							{ label: "启用", value: 1 },
							{ label: "禁用", value: 0 },
						]}
					/>
				</Form.Item>
				<Form.Item>
					<Space>
						<Button type="primary" htmlType="submit">
							搜索
						</Button>
						<Button onClick={() => form.resetFields()}>重置</Button>
					</Space>
				</Form.Item>
			</Form>

			<Button
				type="primary"
				icon={<PlusOutlined />}
				style={{ marginBottom: 16 }}
				onClick={() => {
					setCurrentUser(null);
					setModalVisible(true);
				}}
			>
				新增用户
			</Button>

			<Table
				columns={columns}
				dataSource={data}
				rowKey="id"
				loading={loading}
				pagination={{
					total,
					current: currentPage,
					pageSize,
					onChange: (page, pageSize) => {
						setCurrentPage(page);
						setPageSize(pageSize);
						fetchUsers(page, pageSize);
					},
				}}
			/>

			<UserModal
				visible={modalVisible}
				user={currentUser}
				onSuccess={() => {
					setModalVisible(false);
					fetchUsers();
				}}
				onCancel={() => setModalVisible(false)}
			/>
		</Card>
	);
};

export default UserList;
